package com.qianwei.footpath.ui;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.Toast;
import com.tencent.bugly.crashreport.CrashReport;
import androidx.fragment.app.FragmentActivity;

import com.common.baselib.runtimepermission.NicePermission;
import com.common.baselib.runtimepermission.NicePermissionListener;
import com.qianwei.footpath.R;
import com.qianwei.footpath.base.BaseActivity;
import com.qianwei.footpath.bean.LocalConfigBean;
import com.qianwei.footpath.iview.IMainView;
import com.qianwei.footpath.manage.DataManager;
import com.qianwei.footpath.manage.LocalCacheDataManage;
import com.qianwei.footpath.manage.SerialPortManager;
import com.qianwei.footpath.manage.TimerManager;
import com.qianwei.footpath.presenter.MainPresenter;

public class MainActivity extends BaseActivity<MainPresenter> implements IMainView {
    private static final String TAG = "MainActivity";
    private long mExitTime;
    private ImageView ivStart;
    private long startTime = 0;
    private static final long TIME_LIMIT = 5000; // 5秒
    private static final int CLICK_LIMIT = 10; // 10次
    private int clickCount = 0;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(MainActivity.this);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ivStart = findViewById(R.id.ivStart);
        startZoomAnimation();
        ivStart.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), TestInfo.class));
            SerialPortManager.getInstance(getContext()).openPort();
        });
        findViewById(R.id.daiji_zi).setOnClickListener(v -> clickToConfigActivity());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPhoneStatePermission();
        } else {
            setImei();
        }
    }

    private void startZoomAnimation() {
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(ivStart, "scaleX", 1f, 1.2f);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(ivStart, "scaleY", 1f, 1.2f);
        scaleXAnimator.setDuration(1000);
        scaleYAnimator.setDuration(1000);
        scaleXAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleYAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleXAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleYAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleXAnimator.setRepeatMode(ValueAnimator.REVERSE);
        scaleYAnimator.setRepeatMode(ValueAnimator.REVERSE);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
        animatorSet.start();
    }

    private void clickToConfigActivity() {
        long currentTime = System.currentTimeMillis();

        if (currentTime - startTime > TIME_LIMIT) {
            // 超过时间限制，重新开始计数
            clickCount = 1;
            startTime = currentTime;
        } else {
            // 在时间限制内，增加点击次数
            clickCount++;
            startTime = currentTime;

            if (clickCount >= CLICK_LIMIT) {
                // 达到点击次数限制，显示吐司
                runOnUiThread(() -> startActivity(new Intent(getContext(), ConfigActivity.class)));
                // 重置计数
                clickCount = 0;
                startTime = 0;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SerialPortManager.getInstance(getContext()).release();
    }

    private void checkPhoneStatePermission() {
        new NicePermission((FragmentActivity) getContext(), new NicePermissionListener() {
            @Override
            public void onGranted() {
                setImei();
            }

            @Override
            public void onRefused() {
                showToastMsg("请授权权限");
            }
        }).requestPermission(Manifest.permission.READ_PHONE_STATE);
    }

    private void setImei() {
        String imei = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(imei)) {
            DataManager.getInstance().setImei(imei);
            LocalConfigBean localConfigBean = LocalCacheDataManage.getLocalConfigData();
            localConfigBean.setImei(imei);
            LocalCacheDataManage.setLocalConfigData(localConfigBean);
            CrashReport.setDeviceId(getContext(), imei);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if (event.getRepeatCount() == 0) {
                if (currentTime - mExitTime > 2000) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    mExitTime = currentTime;
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        TimerManager.getInstance().stopAllTimers();
        super.onDestroy();
    }
}
